package com.example.tourism.service.impl;

import com.example.tourism.mapper.OrderMapper;
import com.example.tourism.pojo.Result;
import com.example.tourism.pojo.mo.HotelOrderMO;
import com.example.tourism.pojo.po.*;
import com.example.tourism.pojo.vo.req.CommentReq;
import com.example.tourism.pojo.vo.req.GetOrderListVo;
import com.example.tourism.pojo.vo.req.OrdersReq;
import com.example.tourism.pojo.vo.res.*;
import com.example.tourism.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.example.tourism.pojo.Result.success;
import static java.time.LocalTime.now;
import static java.time.format.DateTimeFormatter.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private  OrderMapper  orderMapper;

    @Autowired
    private RabbitMQSenderService  rabbitMQSenderService;

    @Override
    public Result getOrderHotel(String roomId) {
        // 得到酒店的订单信息
//        System.out.println("酒店房间id:"+roomId);
        HotelOrderMO hotelMOByRoomId = orderMapper.getHotelMOByRoomId(roomId);
        if (hotelMOByRoomId != null) {
            return success(hotelMOByRoomId);
        }else{
            return  Result.error(500,"没有该宾馆");
        }
    }

    @Override
    public Result getCustomers(String userId) {
        // 得到酒店的顾客信息
        System.out.println("用户id:"+userId);
        Customer customers = orderMapper.getCustomers(userId);
        if(customers != null){
            return success(customers);
        }
        else{
            return  Result.error(500,"没有填写顾客信息");
        }
    }

    @Override
    public Result getCoupons(String userId, String roomId) {
        // 查询酒店id
        String hotelId = orderMapper.selectHotelIdByRoomId(roomId);
        System.out.println("酒店id:"+hotelId);
        // 查询用户对该酒店的优惠券
        List<Integer> couponIds = orderMapper.getUserCoupons(userId, hotelId);
        List<CouponRes> coupons = new ArrayList<>();
        for (Integer i : couponIds){
            System.out.println("优惠券id:"+i);
            Coupon coupon = orderMapper.getCouponById(i);
            CouponRes couponRes = new CouponRes();
            couponRes.setId(coupon.getCouponId());
            couponRes.setName(coupon.getName());
            couponRes.setDescription("惊喜立减券");
            couponRes.setExpire(coupon.getEndDate());
            couponRes.setDiscount(Integer.valueOf(coupon.getDiscount()));
            couponRes.setMinSpend(Integer.valueOf(coupon.getMinSpend()));
            coupons.add(couponRes);
        }
        return success(coupons);
    }


    @Override
    synchronized public Result createOrder(OrdersReq ordersReq) {
        // 创建订单
        Orders orders = new Orders();
        // 生成订单编号
        //String uid = OrderNumberGenerator.generateOrderNumber();
        UUID uniqueKey = UUID.randomUUID();
        orders.setOrderUid(uniqueKey.toString());
        orders.setUserId(ordersReq.getUserId());
        orders.setRoomId(ordersReq.getRoomId());
        orders.setPrice(Double.valueOf(ordersReq.getPrice()));
        orders.setStatus(0);  // 设置状态
        orders.setCreateTime(LocalDateTime.now());  // 现在
        orders.setCheckIn(LocalDate.parse(ordersReq.getCheckIn()));
        orders.setCheckOut(LocalDate.parse(ordersReq.getCheckOut()));
        orders.setCustomerName(ordersReq.getCustomerName());
        orders.setPhone(ordersReq.getPhone());
        orders.setEmail(ordersReq.getEmail());
        orders.setType(0);
        System.out.println("优惠券id:" + ordersReq.getCouponId());

        // 确保 orders 对象不为 null
        if (ordersReq.getCouponId() != null) {
            // 尝试将 ordersReq.getCouponId() 转换为 Integer
            try {
                orders.setCouponId(Integer.valueOf(ordersReq.getCouponId()));
                // 修改用户优惠券的状态
                int i = orderMapper.updateCouponStatus(orders.getCouponId(), orders.getUserId());
                if (i == 0) {
                    return Result.error(500, "优惠券使用失败");
                }
            } catch (NumberFormatException e) {
                // 如果转换失败，打印错误信息
                System.out.println("优惠券id格式错误: " + ordersReq.getCouponId());
            }
        }
       System.out.println("订单:" + orders);

        // 插入订单
        try {
            // 先查询订单是否合法
            int count = orderMapper.selectCountByRoomId(orders.getRoomId(), orders.getCheckIn(), orders.getCheckOut());
            if (count > 0) {
                return Result.error(500, "该时间段已经预定");
            } else {
                int insert = orderMapper.insertOrders(orders);
                if (insert == 0) {
                    return Result.error(500, "订单创建失败");
                }
                // 订单创建成功,发送延迟信息
                rabbitMQSenderService.send(orders.getOrderUid());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "订单创建失败");
        }

        return success(orders.getOrderUid());
    }

    @Override
    public Result getOverOrdersTime(String roomId) {
        // 获取该房间已经预定的日期
        List<OrderTime> orderTimes = orderMapper.selectOverOrdersTime(roomId);
        return success(orderTimes);
    }

    @Override
    public Result hotelGetOrderData(GetOrderListVo getOrderListVo) {
        // 分页查询得到订单列表
        int start = (getOrderListVo.getPage() - 1) * getOrderListVo.getPageSize();
        System.out.println("开始:" + start);
        List<OrderVo> orders = null;
        int totalOrders = 0;
        if(getOrderListVo.getSearchKey() == null ||getOrderListVo.getSearchKey().equals("")) {
            orders = orderMapper.selectHotelOrderList(getOrderListVo.getUserId(), start, getOrderListVo.getPageSize());
            totalOrders = orderMapper.selectHotelOrderCount(getOrderListVo.getUserId());
        }else {
            orders = orderMapper.selectHotelOrderListByKey(getOrderListVo.getUserId(), getOrderListVo.getSearchKey(), start, getOrderListVo.getPageSize());
            totalOrders = orderMapper.selectHotelOrderCountByKey(getOrderListVo.getUserId(), getOrderListVo.getSearchKey());
        }
        if (orders != null) {
            orders.forEach(o -> {
                if (o.getCheckOut() != null && LocalDate.now().isAfter(o.getCheckOut())) {
                    o.setStatus("已完成");
                } else if (o.getCheckIn() != null && LocalDate.now().isBefore(o.getCheckIn())) {
                    o.setStatus("待入住");
                } else {
                    o.setStatus("已入住");
                }
            });
        }

        OrderListVo orderListVo = new OrderListVo();
        System.out.println("订单列表:" + orders + ",总数:" + totalOrders);
        orderListVo.setOrders(orders);
        orderListVo.setTotalOrders(totalOrders);
        return success(orderListVo);
    }

    @Override
    public Result clientGetOrderData(GetOrderListVo getOrderListVo) {

        int start = (getOrderListVo.getPage() - 1) * getOrderListVo.getPageSize();
        System.out.println("开始:" + start);
        List<Orders> orders = null;
        int totalOrders = 0;
        if (getOrderListVo.getSearchKey() == null || getOrderListVo.getSearchKey().equals("")) {
            orders = orderMapper.selectClientOrderList(getOrderListVo.getUserId(), start, getOrderListVo.getPageSize());
            totalOrders = orderMapper.selectClientOrderCount(getOrderListVo.getUserId());
        } else {
            orders = orderMapper.selectClientOrderListByKey(getOrderListVo.getUserId(), getOrderListVo.getSearchKey(), start, getOrderListVo.getPageSize());
            totalOrders = orderMapper.selectClientOrderCountByKey(getOrderListVo.getUserId(), getOrderListVo.getSearchKey());
        }
        List<ClientOrderVo> clientOrderVos = new ArrayList<>();
        if (orders != null) {
            orders.forEach(o -> {
                ClientOrderVo clientOrderVo = new ClientOrderVo();
                clientOrderVo.setOrderUid(o.getOrderUid());
                clientOrderVo.setPrice(String.valueOf(o.getPrice()));
                clientOrderVo.setCheckIn(String.valueOf(o.getCheckIn()));
                clientOrderVo.setCheckOut(String.valueOf(o.getCheckOut()));
                clientOrderVo.setCustomerName(o.getCustomerName());
                clientOrderVo.setCreateTime(String.valueOf(o.getCreateTime()));
                clientOrderVo.setPhone(o.getPhone());
                if (o.getStatus() == 0) {
                    clientOrderVo.setStatus("待支付");
                } else if (o.getStatus() == 1) {
                    clientOrderVo.setStatus("已支付");
                } else if (o.getStatus() == 2) {
                    clientOrderVo.setStatus("已取消");
                }
                // 房间信息
                Room room = orderMapper.getRoomByOrderUid(o.getRoomId());
                clientOrderVo.setName(room.getName());
                clientOrderVo.setType(room.getType());
                // 检测订单是否已经评论
                Integer i = orderMapper.selectCommentByOrderUid(o.getOrderUid());
                clientOrderVo.setIsEvaluate(i);
                clientOrderVos.add(clientOrderVo);
            });
            System.out.println("顾客订单列表:" + orders + ",总数:" + totalOrders);
        }

        // 包装数据
        ClientOrderListVo clientOrderListVo = new ClientOrderListVo();
        clientOrderListVo.setTotalOrders(totalOrders);
        clientOrderListVo.setOrders(clientOrderVos);
        return success(clientOrderListVo);
    }

    @Override
    public Result cancelOrder(String orderUid) {
        // 修改订单的状态
        System.out.println("订单Uid"+orderUid);
        int update = orderMapper.updateOrderCancelStatus(orderUid, 2);
        if (update == 1) {
            return success("取消成功");
        }
        return Result.error(500, "订单取消失败");
    }

    @Override
    public Result submitComment(CommentReq comment) {
        Comment commentPo = new Comment();
        commentPo.setOrderUid(comment.getOrderId());
        Integer s = orderMapper.selectHotelIdByOrderUid(comment.getOrderId());
        commentPo.setHotelId(s);

        commentPo.setMessage(comment.getMessage());
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = ofPattern("yyyy-MM-dd HH:mm:ss");
        commentPo.setTime(now.format(formatter));
        commentPo.setRating(comment.getRating());
        // 插入评论
        try {
            int insert = orderMapper.insertComment(commentPo);
            if (insert == 0) {
                return Result.error(500, "评论失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "评论失败");
        }
        return success("评论成功");
    }

    @Override
    public Result insertCoupon(Coupon coupon, String userId) {
      String  hotelId = orderMapper.selectHotelIdByUserId(userId);
        coupon.setHotelId(hotelId);
        try {
            int insert = orderMapper.insertCoupon(coupon);
            if (insert == 0) {
                return Result.error(500, "优惠券发放失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "优惠券发放失败");
        }
        return success("优惠券发放成功");
    }

    @Override
    public Result getHotelCoupons(String userId) {
        // 得到酒店id
        String hotelId = orderMapper.selectHotelIdByUserId(userId);
        List<Coupon> coupons = orderMapper.getCoupons(hotelId);
        if(coupons != null){

            return success(coupons);
        }
        else{
            return  Result.error(500,"没有优惠券");
        }
    }

    @Override
    public Result getHotelCouponsByHotelId(String hotelId) {
        // 获取优惠券
        List<Coupon> coupons = orderMapper.getCoupons(hotelId);
        List<HotelCouponsRes>  hotelCouponsReses = new ArrayList<>();
        for (Coupon c : coupons) {
            HotelCouponsRes hotelCoupon = new HotelCouponsRes();
            hotelCoupon.setId(c.getCouponId());
            hotelCoupon.setName(c.getName());
            hotelCoupon.setDescription("限时抢购");
            hotelCoupon.setRemaining(Integer.valueOf(c.getQuantity()));
            // 计算倒计时(enddate - now)
            LocalDateTime nowDateTime = LocalDateTime.now();
            LocalDateTime issueDateTime = LocalDateTime.parse(c.getIssueDate(), ofPattern("yyyy-MM-dd HH:mm:ss"));
//            DateTime = LocalDateTime.parse(c.getStartDate(), ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime endDateTime = LocalDateTime.parse(c.getEndDate(), ofPattern("yyyy-MM-dd HH:mm:ss"));
            // 计算秒数,秒杀倒计时
            long secondsBetween = ChronoUnit.SECONDS.between(nowDateTime, issueDateTime);

            // 设置秒杀时间
            hotelCoupon.setTimeLeft(secondsBetween);
            if (ChronoUnit.SECONDS.between(nowDateTime, endDateTime) > 0) {
                hotelCoupon.setEndTime(c.getEndDate().formatted("yyyy-MM-dd HH:mm:ss"));
                hotelCouponsReses.add(hotelCoupon);
            }

        }
       return success(hotelCouponsReses);
    }

//    @Override
//    public Result grabCoupon(String couponId, String userId) {
//        // 抢购优惠券
//        // 判断优惠券是否存在库存
//        int quantity = orderMapper.selectCouponQuantity(couponId);
//        if (quantity == 0) {
//            return Result.error(500, "优惠券已经抢光了");
//        }
//        // 判断用户是否已经抢购过
//        int count = orderMapper.selectCouponCount(couponId, userId);
//        if (count > 0) {
//            return Result.error(500, "您已经抢购过该优惠券");
//        }
//        // 抢购
//        System.out.println("优惠券id:"+couponId);
//        System.out.println("用户id:"+userId);
//        // 插入用户优惠券表
//        int i = orderMapper.insertUserCoupon( userId,couponId);
//        if (i == 0) {
//            return Result.error(500, "抢购失败");
//        }
//        // 更新优惠券库存
//        int update = orderMapper.updateCoupon(couponId, userId);
//        if (update == 1) {
//            return success("抢购成功");
//        }
//       return Result.error(500, "抢购失败");
//    }

    @Override
    public Result getMyCoupons(String userId) {
        // 查询用户优惠券
        List<MyCouponRes> coupons = orderMapper.getMyCoupons(userId);
        return   success(coupons);
    }


}
